package com.voltmaon.shortlink.controller;

import com.voltmaon.shortlink.util.ResponseContent;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.bind.annotation.*;
import com.voltmaon.shortlink.service.ShortLinkService;
import com.voltmaon.shortlink.vo.ShortLinkVO;
import lombok.AllArgsConstructor;
import reactor.core.publisher.Mono;

/**
 * @author lfj
 */
@RestController
@AllArgsConstructor
public class RedirectController {
	private final ShortLinkService shortLinkService;

	@GetMapping("/{shortLink}")
	public Mono<Void> redirect(ServerHttpResponse response, String auth, @PathVariable String shortLink) {
		return shortLinkService.redirect(response, shortLink, auth);
	}

	@GetMapping("/authy/{shortLink}")
	public Mono<Void> authRedirect(ServerHttpResponse response, String auth, @PathVariable String shortLink) {
		return shortLinkService.authRedirect(response, shortLink, auth);
	}

	@GetMapping("/verif/{shortLink}")
	public ResponseContent verifAuth(ServerHttpResponse response, String auth, @PathVariable String shortLink) {
		return shortLinkService.verifAuth(response, shortLink, auth);
	}

	@PutMapping("/")
	public ResponseContent authRedirect(@RequestBody ShortLinkVO vo) {
		vo.setFullLink(vo.getFullLink()
			.trim());
		if(vo.getFullLink()
			.startsWith("http://") || vo.getFullLink()
			.startsWith("https://")) {
			return shortLinkService.save(vo);
		} else {
			throw new RuntimeException("网址必须以http或https开头");
		}
	}
}